<template>
  <div>
    <!--    列表页-->
    <el-button type="primary" icon="el-icon-plus" @click="addTrademark">添加</el-button>
    <el-table
      :data="trademarkList"
      style="width: 100%;margin-top: 20px" border>
      <el-table-column
        prop="prop"
        align="center"
        type="index"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="width">
      </el-table-column>
      <el-table-column
        prop="prop"
        label="品牌LOGO"
        width="width">
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl" alt="" style="width: 100px;height: 80px;">
        </template>
      </el-table-column>
      <el-table-column
        prop="prop"
        label="操作"
        width="width">
        <template slot-scope="{row,$index}">
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="updateTrademark(row)">修改</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteTrademark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="getTrademarkList"
      :current-page="page"
      align="center"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      :pager-count="7"
      layout=" prev, pager, next, jumper, ->, sizes, slot,total"
      :total="total">
    </el-pagination>
    <!--   dialog对话框页面 -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form ref="tmForm" :model="tmForm" :rules="rules" style="width: 80%">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model='tmForm.tmName' autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TrademarkList",
  data() {
    var validateTmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 20) {
        callback(new Error("品牌名称的长度必须在2-20之间"));
      } else {
        callback();
      }
    };
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],
      dialogFormVisible: false,
      // form指定收集数据的位置
      tmForm: {
        tmName: '',
        logoUrl: "",//图片相关
      },
      //验证规则
      rules: {
        // trigger  触发方式 验证时机
        // blur失去焦点   change改变内容   整体验证的时候触发
        tmName: [
          {required: true, message: "品牌名称必须有", trigger: "blur"},
          {validator: validateTmName, trigger: "change"},
          // {
          //   min: 2,
          //   max: 10,
          //   message: "长度在 2 到 10 个字符",
          //   trigger: "change",
          // },
        ],
        logoUrl: [{required: true, message: "请选择品牌LOGO"}],
      },
    }
  },
  mounted() {
    this.getTrademarkList()
  },
  methods: {
    //获取数据
    async getTrademarkList(pager = 1) {
      this.page = pager
      const result = await this.$API.trademark.getPageList(this.page, this.limit)
      if (result.code === 200 || result.code === 20000) {
        this.trademarkList = result.data.records
        this.total = result.data.total
      }
    },
    //从el官网复制过来的回调函数1
    handleSizeChange(size) {
      this.size = size
      this.getTrademarkList()
    },
    //图片上传相关的函数 官网复制过来的
    handleAvatarSuccess(res, file) {
      /*this.imageUrl = URL.createObjectURL(file.raw);*/
      this.tmForm.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //点击添加按钮
    addTrademark() {
      this.dialogFormVisible = true
      //清空一下dialog对话框
      this.tmForm = {
        tmName: '',
        logoUrl: "",//图片相关
      }
    },
    //点击修改按钮 切换到修改品牌页 添加和修改用的是同一个页面
    updateTrademark(row) {
      this.dialogFormVisible = true//打开dialog对话框
      this.tmForm = {...row}//
    },
    //点击确定按钮 发请求 返回列表页
    save() {
      this.$refs.tmForm.validate(async (valid) => {
        if (valid) {
          //获取参数 整理参数
          let trademark = this.tmForm
          try {
            const result = await this.$API.trademark.addOrUpdate(trademark)
            if (result.code === 200 || result.code === 20000) {
              //弹出成功的信息
              this.$message.success(trademark.id ? '修改品牌成功' : '添加品牌成功')
              //关闭dialog
              this.dialogFormVisible = false
              //返回父组件列表页 父组件里有分页器需要考虑到分页
              await this.getTrademarkList(trademark.id > 1 ? this.page : 1)
            } else {
              this.$message.error(trademark.id ? '修改品牌失败' : '添加品牌失败')
            }
          } catch (error) {
            this.$message.error(trademark.id ? '修改品牌请求失败' : '添加品牌请求失败')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //点击删除按钮 通过id 发请求 删除数据库的信息 然后重新获取数据 渲染页面
    deleteTrademark(row) {
      this.$confirm(`你确定要删除${row.tmName}吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$API.trademark.delete(row.id)
          this.$message.success('删除品牌成功')
          //删除成功后要看当前页面有几个 如果比1大 就停留在当前页,如果只有一个 就去上一页
          await this.getTrademarkList(this.trademarkList.length > 1 ? this.page : this.page - 1)
        } catch (error) {
          this.$message.error('删除品牌失败' + error.message)
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
